package com.hanggold.netty.server;

import com.hanggold.netty.handler.EchoDemo2ServerHandler;
import com.hanggold.netty.handler.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * TODO COMMENT.
 *
 * @author <a href="mailto:sunmch@163.com">smc</a>
 * @date 2021-11-25 21:57
 * @since 1.0.0
 **/
public class EchoServer {
    
    private static final Logger logger = LoggerFactory.getLogger(EchoServer.class);
    
    private final int port;
    
    public EchoServer(int port) {
        this.port = port;
    }
    
    public void start() throws InterruptedException {
        final EchoServerHandler echoServerHandler = new EchoServerHandler();
        
        final EchoDemo2ServerHandler echoDemo2ServerHandler = new EchoDemo2ServerHandler();
        
        final NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        
        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        
        serverBootstrap.group(eventExecutors).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(final SocketChannel socketChannel) throws Exception {
                
                socketChannel.pipeline().addLast(echoServerHandler, echoDemo2ServerHandler);
                //                socketChannel.pipeline().addBefore()
            }
        });
        
        final ChannelFuture future = serverBootstrap.bind().sync();
        future.channel().closeFuture().sync();
        logger.info("start success");
        eventExecutors.shutdownGracefully().sync();
    }
    
    public static void main(String[] args) throws InterruptedException {
        final EchoServer echoServer = new EchoServer(8880);
        echoServer.start();
    }
    
}
